<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Usuarios extends CI_Controller {

	function __construct() {
		parent::__construct();
		if(!$this->session->userdata('disproju')){
			$this->session->sess_destroy();
			redirect('login', 'refresh');
		}
	}
	
	public function index()	{
		redirect('usuarios/consulta');
	}
	public function novo(){
		//******************************************************
		//   PERMISSAO 
		//******************************************************
		$session_data = $this->session->userdata('disproju');
		temPermissao(array('1','2'),$session_data);
		//seleciona permissao do banco de dados
		
		$perm = new Permissao();
		/*$perm = $perm->get();
		$permissao = array();
		foreach($perm as $p){
			$permissao[$p->id ] = $p->nome_permissao;
		}
		*/
		
		$data['permissao'] = $perm->consultaPermissao('3');
		//$data['permissao'] = $permissao;
		
		$this->load->view('header');
		$this->load->view('v_usuario',$data);
	}
	
	public function consultaUserAD() {
		
		//******************************************************
		//   PERMISSAO 
		//******************************************************
		$session_data = $this->session->userdata('disproju');
		temPermissao(array('1','2'),$session_data);
	
		//$term = $_GET['q'];
		
		// Active Directory server
		$ldap_host = "tucano.arapongas.pr.gov.br";

		// Active Directory DN
		$ldap_dn = "OU=Procuradoria Juridica,OU=SEGOV,OU=PMA,OU=Usuarios,DC=arapongas,DC=pr,DC=gov,DC=br";

		// Domain, for purposes of constructing $user
		$ldap_usr_dom = "@arapongas.pr.gov.br";
		// Domain, for purposes of constructing $user
		//$ldap_usr_dom = "@".$ldap_host;
	 
		// Active Directory user
		$user = "usuario.comum";
		$password = "urubu11";
	 
		// User attributes we want to keep
		// List of User Object properties:
		// http://www.dotnetactivedirectory.com/Understanding_LDAP_Active_Directory_User_Object_Properties.html
		$keep = array("samaccountname","displayname");
	 
		// Connect to AD
		$ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
		ldap_bind($ldap,$user.$ldap_usr_dom,$password) or die("Could not bind to LDAP");
	 
		// Begin building query
		

		$query = "(&(objectClass=user)(objectCategory=person)(userAccountControl=512))";

		
		$results = ldap_search($ldap,$ldap_dn,$query);
					
		$entries = ldap_get_entries($ldap, $results);
	 
		// Remove first entry (it's always blank)
		array_shift($entries);
	 
		$output = array(); // Declare the output array
	 
		$i = 0; // Counter
		// Build output array
		foreach($entries as $u) {
			foreach($keep as $x) {
				// Check for attribute
				if(isset($u[$x][0])) $attrval = $u[$x][0]; else $attrval = NULL;

				// Append attribute to output array
				$output[$i][$x] = $attrval;
			}
			$i++;
		}
	 
		asort($output);
		
		$aux = array();
		$dados = array();
		
		foreach($output as $u){
			if(substr_compare($u["samaccountname"], $_GET['term'], 0, 1, true) == 0){
				$aux["value"] = $u["samaccountname"];
				$aux["name"] = $u["samaccountname"];
				$aux["fullname"] = utf8_encode($u["displayname"]);
				array_push($dados,$aux);
			}

		}
		echo json_encode($dados);

	}
	public function salvar(){
	
		//******************************************************
		//   PERMISSAO 
		//******************************************************
		$session_data = $this->session->userdata('disproju');
		temPermissao(array('1','2'),$session_data);
		
		if($this->input->post()){
		
			$u = new Usuario();
			
			$u->permissao_id =  strtoupper($this->input->post('permissao'));
			if($this->input->post('excecao')){
				$u->excecao = $this->input->post('excecao');
			}
			$u->login = strtolower($this->input->post('login'));
			$nome =  mb_strtoupper($this->input->post("nome"), 'UTF-8');
			$u->nome_completo = $nome;
			$u->observacao = strtoupper($this->input->post('observacao'));
			
			$tipoprocesso = new TipoProcesso();
			 //CASO USUARIO SEJA ADVOGADO
                        if($u->permissao_id == '3'){
                                if($this->input->post("processos")){
                                        $tipoprocesso->where_in("id",$this->input->post("processos"))->get();
                                        foreach($tipoprocesso as $t){
                                                if($u->save($t)){
                                                        $acao = $t->check_last_query(false,true);
                                                        $log = new Log();
                                                        $log->ip = $this->session->userdata('ip_address');
                                                        $log->usuario = $session_data["nome"];
                                                        $log->acao = $acao;
                                                        $log->dt_log = date('Y-m-d H:i:s');
                                                        $log->save();

                                                }else{
                                                        echo 'Erro Ao salvar';
                                                }
                                        }
                                        echo 'OK';

                                }else{
                                        if($u->save()){
                                                $acao = $u->check_last_query(false,true);
                                                $log = new Log();
                                                $log->ip = $this->session->userdata('ip_address');
                                                $log->usuario = $session_data["nome"];
                                                $log->acao = $acao;
                                                $log->dt_log = date('Y-m-d H:i:s');
                                                $log->save();
                                                echo 'OK';
                                        }else{
                                                echo 'Erro Ao salvar';
                                        }
                                }
			/*
			//CASO USUARIO SEJA ADVOGADO
			if($u->permissao_id == '3'){
				//if($this->input->post("processos") && sizeof($this->input->post("processos")) < 3){
				if($this->input->post("processos")){
				
					$tipoprocesso->where_in("id",$this->input->post("processos"))->get();
					foreach($tipoprocesso as $t){
						if($u->save($t)){
							$acao = $t->check_last_query(false,true);
							$log = new Log();
							$log->ip = $this->session->userdata('ip_address');
							$log->usuario = $session_data["nome"];
							$log->acao = $acao;
							$log->dt_log = date('Y-m-d H:i:s');
							$log->save();
							
						}else{
							echo 'Erro Ao salvar';
						}
					}
					echo 'OK';
				
					echo 'PROCESSOS';
				}else{
					$tipoprocesso->get();
					if($u->save($tipoprocesso->all)){
						$acao = $u->check_last_query(false,true);
						$log = new Log();
						$log->ip = $this->session->userdata('ip_address');
						$log->usuario = $session_data["nome"];
						$log->acao = $acao;
						$log->dt_log = date('Y-m-d H:i:s');
						$log->save();
						echo 'OK';
					}else{
						echo 'Erro Ao salvar';
					}
				
					echo 'EXCECAO';
				}
				print_r($this->input->post());
			*/
			}else{
				if($u->save()){
					$acao = $u->check_last_query(false,true);
					$log = new Log();
					$log->ip = $this->session->userdata('ip_address');
					$log->usuario = $session_data["nome"];
					$log->acao = $acao;
					$log->dt_log = date('Y-m-d H:i:s');
					$log->save();
					echo 'OK';
				}else{
					//seleciona permissao do banco de dados
					$perm = new Permissao();
					$data['permissao'] = $perm->consultaPermissao('3');
					$data['usuario']  = $u;
					$this->load->view('v_usuario',$data);
				}
			}
			echo $u->error->string;
		}
	}
	public function editar(){
	
		//******************************************************
		//   PERMISSAO 
		//******************************************************
		$session_data = $this->session->userdata('disproju');
		temPermissao(array('1','2'),$session_data);
		
		$id =  $this->input->post('id');
		
		$p = new Usuario();
		$p->where('id', $id)->get();
		
		$p->login =  strtoupper($this->input->post('login'));
		$p->nome_completo =  strtoupper($this->input->post('nome'));
		$p->permissao_id = $this->input->post('permissao');
		$p->status = strtoupper($this->input->post('status'));
		$p->observacao = strtoupper($this->input->post('observacao'));
		
		
		
		if($p->permissao_id == '3'){
			$tipoprocesso = new TipoProcesso();
			$tipoprocesso->get();
			if($p->save($tipoprocesso->all)){
				//redirect('usuarios/consulta');
				echo 'OK';
			}else{
				$p->include_related('permissao', array('nome_permissao'))->get();
				$data['usuario']  = $p;
				$this->load->view('v_usuario_info',$data);
			}
		}else{
			$tu = new TipoProcesso_Usuario();
			$tu->where('usuario_id', $p->id)->get();
			$tu->delete_all();
			
			if($p->save()){
				//redirect('usuarios/consulta');
				echo 'OK';
			}else{
				$p->include_related('permissao', array('nome_permissao'))->get();
				$data['usuario']  = $p;
				$this->load->view('v_usuario_info',$data);
			}
		}
		
				
		echo $p->error->string;
		
	
		
	}
	public function consulta(){
		//******************************************************
		//   PERMISSAO 
		//******************************************************
		$session_data = $this->session->userdata('disproju');
		temPermissao(array('1','2'),$session_data);
		
		$p = new Usuario();
		$aux = new Usuario();
		$aux = $p->consulta();
	
		$data['usuario']  = $aux;
		
		$this->load->view('header');
		$this->load->view('v_usuario_consulta',$data);
	}
	public function info($id = NULL){
		
		//******************************************************
		//   PERMISSAO 
		//******************************************************
		$session_data = $this->session->userdata('disproju');
		temPermissao(array('1','2'),$session_data);
		
		if( ! empty($id))
		{
			$p = new Usuario();
			$p->get_by_id($id);
			if( ! $p->exists())
			{
				show_error('Invalid User ID');
			}
		}

		$data['usuario'] = $p;
		
		$perm = new Permissao();
		$data['permissao'] = $perm->consultaPermissao('3');
		
		$ausente = new Ausente();
		$ausente->where("usuario_id",$id)->order_by('id desc')->get();
		
		$data['ausente'] = $ausente;
		
		$this->load->view('header');
		$this->load->view('v_usuario_info',$data);
	}
	public function validaUsuario(){
		$login = $_GET['login'];
		
		$p = new Usuario();
		$p->get_by_login($login);
		if( ! $p->exists())
		{
			//return true;
			echo "true";
		}else{
			//return false;
			echo "false";
		}

	}
	public function consultaUsuario(){
		$u = new Usuario();
		$this->where('permissao_id', "3")->get();
		
		$user = array();
		foreach($u as $a){
			$user[$a->id ] = $a->nome_completo;
		}
		
		return $user;

	}
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
